<?php
class Tools {
	/**
	 * 检查身份证号是否正确
	 *
	 * @param string $sNo 18位身份证号
	 * @return bool
	 */
	public function checkIDCard($sNo) {
		$sNo = strtoupper ( $sNo );
		$sDate = substr ( $sNo, 6, 4 ) . '-' . substr ( $sNo, 10, 2 ) . '-' . substr ( $sNo, 12, 2 );
		if ($sDate == date ( 'Y-m-d', strtotime ( $sDate ) )) {
			if ($sNo == substr ( $sNo, 0, 17 ) . self::_getIDCardVerify ( $sNo )) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
	}
	
	/**
	 * 身份证号15为升级为18位
	 *
	 * @param string $sNo 15位身份证号
	 * @return string 18位身份证号
	 */
	public function getIDCard15218($sNo) {
		$sNo = substr ( $sNo, 0, 6 ) . '19' . substr ( $sNo, 6 );
		return $sNo . self::_getIDCardVerify ( $sNo );
	}
	
	private function _getIDCardVerify($sNo) {
		$aQuotiety = array (7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2 );
		$aReplace = array (1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2 );
		$iSum = 0;
		for($i = 0; $i < 18; $i ++) {
			$iSum += intval ( $sNo {$i} * $aQuotiety [$i] );
		}
		return $aReplace [$iSum % 11];
	}
	
	/**
	 * 对字符串进行编码
	 * 
	 * @param string $sString 需编码的字符串
	 * @param string $sKey 
	 * @return string
	 */
	public function encode($sString, $sKey = null) {
		$iLength = strlen ( $sString );
		$iLimit = 32 - $iLength % 32;
		$sString .= str_repeat ( chr ( 0 ), $iLimit );
		$iSleep = strlen ( $sString ) / 32;
		$sKey = md5 ( $sKey );
		$sCode = '';
		for($i = 0; $i < $iSleep; $i ++) {
			$sStr = substr ( $sString, $i * 32, 32 );
			$sCode .= $sStr ^ $sKey;
		}
		$sCode = substr ( $sCode, 0, $iLength );
		$sString = base64_encode ( $sCode );
		return $sString;
	}
	
	/**
	 * 对编码后的字符串进行解码
	 * 
	 * @param string $sString
	 * @param string $sKey
	 * @return string
	 */
	public function decode($sString, $sKey = null) {
		$sString = base64_decode ( $sString );
		$iLength = strlen ( $sString );
		$iLimit = 32 - $iLength % 32;
		$sString .= str_repeat ( chr ( 0 ), $iLimit );
		$iSleep = strlen ( $sString ) / 32;
		$sKey = md5 ( $sKey );
		$sCode = '';
		for($i = 0; $i < $iSleep; $i ++) {
			$sStr = substr ( $sString, $i * 32, 32 );
			$sCode .= $sStr ^ $sKey;
		}
		$sCode = substr ( $sCode, 0, $iLength );
		return $sCode;
	}
}
?>